package com.example.myokhttpdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.IOException;
import java.net.URL;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    Button button;
    URL url;
    ImageView imageView;
    private Handler handler;
    private static final int GET_IMG = 1001;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button=findViewById(R.id.test);
        imageView=findViewById(R.id.image);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AsyncGet();
            }
        });
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == GET_IMG){
                    byte[] picture = (byte[]) message.obj;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(picture,0,picture.length);
                    imageView.setImageBitmap(bitmap);     // 主线程修改UI
                }
                return true;
            }
        });
    }

    private void AsyncGet(){
        OkHttpClient client=new OkHttpClient();
        MediaType mediaType=MediaType.parse("img/png,charset=utf-8");
        RequestBody requestBody=RequestBody.create(mediaType,"");
        Request request=new Request.Builder()
                .url("https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdl.zhutix.net%2F2018%2F11%2F1917983b557eb57cbec.jpg%3Fx-oss-process%3Dimage%2Fresize%2Cw_1570&refer=http%3A%2F%2Fdl.zhutix.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg")
                .get()
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                byte[] picture = response.body().bytes();
                Log.e("OkHttp","response = " + picture);
                Message message = Message.obtain();
                message.what = GET_IMG;
                message.obj = picture;
                handler.sendMessage(message);
            }
        });
    }
}